import { Component, OnInit } from '@angular/core';
import { ActionSheetController, NavController } from '@ionic/angular';
import { Camera, CameraOptions, PictureSourceType } from '@ionic-native/camera/ngx';

import { MineService } from 'src/app/service/mine.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-photo',
  templateUrl: './photo.component.html',
  styleUrls: ['./photo.component.scss'],
})
export class PhotoComponent implements OnInit {

  photoUrl: string;

  constructor(private router: Router, private camera: Camera, public actionSheetController: ActionSheetController, private navController: NavController, private mineService: MineService) { }

  ngOnInit() {
    this.photoUrl = this.mineService.getPhotoUrl()
    this.mineService.getLoginDataObservable().subscribe(data => this.photoUrl = data.photoUrl)
  }

  async chooseOperation() {
    const actionSheet = await this.actionSheetController.create({
      cssClass: 'photo-operation',
      mode: 'md',
      buttons: [{
        text: '从手机相册选择',
        role: 'destructive',
        handler: () => {
          this.takePicture(PictureSourceType.SAVEDPHOTOALBUM)
        }
      }, {
        text: '拍照',
        role: 'destructive',
        handler: () => {
          this.takePicture(PictureSourceType.CAMERA)
        }
      }, {
        text: '查看上一张头像',
        role: 'destructive',
      }, {
        text: '取消',
        role: 'cancel',
      }]
    });
    await actionSheet.present();
  }

  takePicture(sourceType) {
    const options: CameraOptions = {
      quality: 80, // 图片质量，范围是0-100
      destinationType: this.camera.DestinationType.FILE_URI, // 返回格式，DATA_URL表示base64编码，FILE_URL表示文件地址
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE, // 媒体类型
      sourceType: sourceType, // 图片来源，CAMERA表示摄像机获取，PHOTOLIBRARY表示图库
      correctOrientation: true, // 旋转图像以在捕获过程中校正设备的方向
      allowEdit: false, // 是否允许编辑
      saveToPhotoAlbum: false, // 是否保存到相册
      // targetWidth:300,  // 宽度
      // targetHeight:300, // 高度
    }
    this.camera.getPicture(options).then((data) => {
      // const imageData = 'data:image/jpeg;base64,' + data; //照片的base64数据
      // this.router.navigate(['/person-info/photo-edit'], { queryParams: { fileUrl } })
      this.navController.navigateForward('/person-info/photo-edit', { queryParams: { filePath: data } }).then(() => {
        // this.events.subscribe('crop-image:result', imgBase64Str => {
        //   this.cover = imgBase64Str;//imgBase64Str 是裁剪后base64格式的图片
        // });
      })
    }, (err) => {
      console.log("error", JSON.stringify(err))
    })
  }
}
